package com.taiji.dianthus.api.sys;


import com.taiji.dianthus.common.BasicController;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.dto.UserDto;
import com.taiji.dianthus.service.sys.RoleUserService;
import com.taiji.dianthus.service.sys.SysLogService;
import com.taiji.dianthus.service.sys.UserService;
import com.taiji.dianthus.util.IPUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import static com.taiji.dianthus.common.Constant.*;

/**
 * @ClassName SysUserController
 * @Description
 * @Author H.M
 * @Date 2020/1/8
 */
@Api(value = "用户API")
@RestController
@RequestMapping(value = "/api/user")
public class SysUserController extends BasicController {

    @Autowired
    public UserService userService;

    @Autowired
    public RoleUserService roleUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysLogService sysLogService;

    @RequestMapping(value = "/save")
    @ResponseBody
    @ApiOperation(value = "保存/修改用户方法", notes = "保存/修改用户接口")
    @ApiImplicitParam(name = "form", value = "保存/修改用户", required = true, dataType = "UserDto")
    public BusinessMessage saveRole(@RequestBody UserDto user) {
        //此逻辑只针对角色 用户 1v1 关系
        if (!StringUtils.isEmpty(user.getId()) && !StringUtils.isEmpty(user.getRoleId())) {
            String roleId = roleUserService.getByUser(user.getId());
            if (StringUtils.isEmpty(roleId)) {
                roleUserService.save(user.getRoleId(), user.getId());
            } else {
                if (!roleId.equals(user.getRoleId())) {
                    roleUserService.update(user.getId(), user.getRoleId());
                }
            }
        }
        return userService.add(StringUtils.isEmpty(user.getId()) ? null : user.getId(), user.getName(), user.getUserLoginName(), user.getUserPassword(),
                user.getUserMail(), user.getUserPhone(), user.getOrgId(), null, user.getRoleId());
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    @ApiOperation(value = "删除用户", notes = "删除用户接口")
    @ApiImplicitParam(name = "id", value = "主键", dataType = "string", required = true, paramType = "query")
    public BusinessMessage delete(HttpServletRequest request, String id) {
        BusinessMessage message = new BusinessMessage();
        DSysUser user = userService.getById(id);
        if (null == user) {
            message.setMsg("用户不存在");
            sysLogService.save(currentUser(), LOG_OPERATION_DEL, IPUtil.getIpAddr(request),
                    "删除用户", 0, message.getMsg());
            return message;
        }
        message = userService.delete(id);
        sysLogService.save(currentUser(), LOG_OPERATION_DEL, IPUtil.getIpAddr(request),
                "删除用户[" + user.getName() + "]", message.getSuccess() ? 1 : 0, message.getMsg());
        return message;

    }


    @RequestMapping(value = "/countLoginName")
    @ResponseBody
    @ApiOperation(value = "查询登录名重复", notes = "验证查询登录名重复接口")
    @ApiImplicitParam(name = "userLoginName", value = "登录名", dataType = "string", required = true)
    public BusinessMessage countLoginName(@Param("userLoginName") String userLoginName) {
        BusinessMessage message = new BusinessMessage();
        Integer count = userService.countByLoginName(userLoginName);
        if (count == 0) {
            message.setSuccess(true);
        }
        message.setData(count);
        return message;
    }


    @RequestMapping(value = "/checkPassword")
    @ResponseBody
    @ApiOperation(value = "验证当前用户密码", notes = "验证当前用户密码")
    @ApiImplicitParam(name = "password", value = "密码", dataType = "string", required = true)
    public BusinessMessage checkPassword(@Param("password") String password) {
        BusinessMessage message = new BusinessMessage();
        DSysUser user = currentUser();
        Boolean checkFlag = passwordEncoder.matches(password, user.getUserPassword());

        if (checkFlag) {
            message.setMsg("密码校验成功");
        } else {
            message.setMsg("密码校验失败");
        }
        message.setSuccess(checkFlag);
        return message;
    }

    @RequestMapping(value = "/changePassword")
    @ResponseBody
    @ApiOperation(value = "修改当前用户密码", notes = "修改当前用户密码")
    @ApiImplicitParam(name = "password", value = "密码", dataType = "string", required = true)
    public BusinessMessage changePassword(HttpServletRequest request, @Param("password") String password) {
        BusinessMessage message = new BusinessMessage();
        message = userService.updatePassword(currentUser().getId(), password);
        sysLogService.save(currentUser(), LOG_OPERATION_UPDATE, IPUtil.getIpAddr(request),
                "修改密码", message.getSuccess() ? 1 : 0, message.getMsg());
        return message;
    }

    @RequestMapping(value = "/resetPassword")
    @ResponseBody
    @ApiOperation(value = "重置用户密码", notes = "重置用户的密码")
    @ApiImplicitParam(name = "userId", value = "密码", dataType = "string", required = true, paramType = "query")
    public BusinessMessage resetPassword(HttpServletRequest request, String userId) {
        BusinessMessage message = userService.updatePassword(userId, DEFAULT_PASSWORD);
        DSysUser user = userService.getById(userId);
        if (message.getSuccess()) {
            message.setMsg("密码已经重置为默认密码：" + DEFAULT_PASSWORD);
        }
        sysLogService.save(currentUser(), LOG_OPERATION_UPDATE, IPUtil.getIpAddr(request),
                "重置用户[" + user.getName() + "]密码", message.getSuccess() ? 1 : 0, message.getMsg());
        return message;
    }


}
